<template>
    <div class="message-dialog-container">
        <a-page-header class="a-page-header" :title="target.nickname" :subTitle="targetStatus" />

        <div class="message-content">
            <div class="chat" v-for="(item, index) in chatHistory" :key="index">
                <div class="left message" v-if="item.id == target.id">
                    <a-avatar class="avatar" shape="square" :src="baseURL + target.avatar" />
                    <div class="content">
                        <span v-html="item.message"></span>
                    </div>
                </div>
                <div class="right message" v-if="item.id == user.id">
                    <a-avatar class="avatar" shape="square" :src="baseURL + user.avatar" />
                    <div class="content">
                        <span v-html="item.message"></span>
                    </div>
                </div>
            </div>
        </div>

        <div class="footer">
            <ul class="action">
                <li>
                    <lord-icon class="icon" src="https://cdn.lordicon.com/rrfthkgx.json" trigger="hover"
                        colors="primary:#363636" />
                </li>
                <li>
                    <lord-icon class="icon" src="https://cdn.lordicon.com/dutqakce.json" trigger="hover"
                        colors="primary:#363636" />
                </li>
                <li>
                    <lord-icon class="icon" src="https://cdn.lordicon.com/wtywrnoz.json" trigger="hover"
                        colors="primary:#363636" @click="redirectToVideoCall" />
                </li>
                <li>
                    <lord-icon class="icon" src="https://cdn.lordicon.com/ibjcmcbv.json" trigger="hover"
                        colors="primary:#363636" />
                </li>
                <li style="position: absolute; right: 15px;">
                    <lord-icon class="icon" src="https://cdn.lordicon.com/tewlfgbl.json" trigger="hover"
                        state="loop-scale" colors="primary:#363636" />
                </li>
            </ul>
            <a-textarea class="a-textarea" ref="inputRef" :bordered="false" :maxlength="800" v-model:value="message" />
            <ul class="send">
                <li style="--i:#4be1ec;--j:#cb5eee;" @click="sendMessage">
                    <lord-icon src="https://cdn.lordicon.com/wwsllqpi.json" trigger="hover" colors="primary:#ffffff"
                        class="icon" />
                    <span class="title">发 送</span>
                </li>
            </ul>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, watchEffect, inject } from 'vue'
import { notification } from 'ant-design-vue'
import { useRouter, useRoute } from 'vue-router'
import { GetUserInfo_API, GetUserInfoById_API } from '@/api/user.js'
import { ChatHistory_API } from '@/api/chat.js'
import TIM from '@/assets/audio/TIM.mp3'

const baseURL = import.meta.env.VITE_API_BASE_URL
const socket = inject('socket')
const router = useRouter()
const route = useRoute()

const user = ref({})
const target = ref({})
const targetStatus = ref(null)
const message = ref('')
const chatHistory = ref([]) // 聊天历史记录
const currentTid = ref() // 当前聊天对象的 ID

// 获取用户信息
const getUserInfo = async () => {
    const { data: user_info } = await GetUserInfo_API()
    user.value = user_info.data
    const { data: target_info } = await GetUserInfoById_API(parseInt(route.query.tid))
    target.value = target_info.data
}

// 发送消息
const sendMessage = () => {
    socket.emit('private-chat', route.query.tid, message.value)
    socket.once('private-message-self', (data) => {
        chatHistory.value.push({
            id: data.id,
            message: data.message,
            message_type: data.message_type,
            created_at: data.created_at,
        })
    })
    message.value = ''
    getChatHistory();
}

// 获取聊天记录
const getChatHistory = async () => {
    const { data: res } = await ChatHistory_API(route.query.tid)
    chatHistory.value = res.data
}

const redirectToVideoCall = () => {
    if (targetStatus.value === '离线') {
        notification.error({
            key: 'video-call',
            message: '目标用户当前不在线，无法进行视频通话！'
        })
        return
    }

    if (window.electron) {
        window.electron.videoCallInvoke()
    } else {
        router.push({
            path: '/videoCall',
            query: {
                tid: route.query.tid,
                direction: 'default'
            }
        })
    }
}

// 监听 route.query.tid 的变化，如果 tid 变化了，更新 targetStatus、currentTid 并重新拉取数据
watchEffect(() => {
    if (currentTid.value !== route.query.tid) {
        socket.off('online')
        socket.off('offline')
        socket.emit('target online status', route.query.tid)
        socket.on('online', (message) => {
            targetStatus.value = message
        })
        socket.on('offline', (message) => {
            targetStatus.value = message
        })
        currentTid.value = route.query.tid;
        getUserInfo();
        getChatHistory();
    } else {
        return
    }
});

onMounted(() => {
    getUserInfo()
    getChatHistory()
    currentTid.value = route.query.tid
    // 监听私聊消息：每次收到消息时播放音频
    socket.on('private-message', (data) => {
        chatHistory.value.push({
            id: data.id,
            message: data.message
        })
        const audio = new Audio(TIM)
        audio.play()
    })
})

</script>

<style lang="less" scoped>
.modal {
    border-radius: 0;
}

.message-dialog-container {
    width: 100%;
    height: 100vh;
    display: grid;
    grid-template-rows: 55px 1fr 150px;
    position: relative;

    .a-page-header {
        width: 100%;
        border-bottom: 1px solid #DEDEDE;
        z-index: 0;
    }

    .message-content:hover {
        scrollbar-width: auto;
    }

    .message-content {
        width: 100%;
        // Tips: 这里计算高度时，需要减去 header 和 footer 的高度。 100% 不能参与计算，需要一个更明确的值。
        max-height: calc(100vh - 205px);
        overflow-x: hidden;
        overflow-y: scroll;
        user-select: none;
        position: relative;
        scrollbar-width: none;

        .chat {
            width: 100%;
            height: auto;
            padding-left: 20px;
            padding-right: 20px;

            .message {
                display: flex;
                align-items: flex-end;
                padding: 20px 0;

                .avatar {
                    flex: none;
                    margin: 0 10px;
                    border-radius: 0%;
                }

                .content {
                    span {
                        display: flex;
                        justify-content: space-around;
                        align-items: center;
                        flex-wrap: wrap;
                        max-width: 260px;
                        padding: 0px 18px;
                        min-height: 40px;
                        font-size: 14px;
                        color: rgba(25, 29, 35, 1);
                        line-height: 20px;
                    }
                }
            }

            .left {
                flex-direction: row;

                span {
                    background: white;
                    border-radius: 12px 12px 12px 0px;
                }
            }

            .right {
                flex-direction: row-reverse;

                span {
                    background: #fae4d7;
                    border-radius: 12px 12px 0px 12px;
                }
            }
        }
    }

    .footer {
        width: 100%;
        height: 150px;
        background: #EDEDED;
        position: absolute;
        bottom: 0;
        border-top: 1px solid #DEDEDE;

        .action {
            width: 100%;
            height: 40px;
            list-style: none;
            padding-left: 15px;
            display: flex;
            justify-content: flex-start;
            align-items: center;

            li {
                width: 30px;
                height: 30px;
                display: flex;
                justify-content: center;
                align-items: center;
                margin-right: 5px;

                .icon {
                    width: 20px;
                    height: 20px;
                }
            }

            li:hover {
                background: #E1E1E1;

            }
        }

        .a-textarea {
            padding-left: 20px;
            position: absolute;
            width: 100%;
            max-height: auto;
            border-radius: 0;
            background: #EDEDED;
            resize: none;
            overflow-x: hidden;
            overflow-y: scroll;
        }

        /* From Uiverse.io by elijahgummer */
        .send {
            position: absolute;
            bottom: 15px;
            right: 15px;
            display: flex;
            gap: 25px;
        }

        .send li {
            position: relative;
            list-style: none;
            width: 45px;
            height: 45px;
            border-radius: 60px;
            background-color: #232323;
            cursor: pointer;
            display: flex;
            justify-content: center;
            align-items: center;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            transition: 0.5s;
        }

        .send li:hover {
            width: 160px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0);
        }

        .send li::before {
            content: "";
            position: absolute;
            inset: 0;
            border-radius: 60px;
            background: linear-gradient(45deg, var(--i), var(--j));
            opacity: 0;
            transition: 0.5s;
        }

        .send li:hover::before {
            opacity: 1;
        }

        .send li::after {
            content: "";
            position: absolute;
            top: 10px;
            width: 100%;
            height: 100%;
            border-radius: 60px;
            background: linear-gradient(45deg, var(--i), var(--j));
            transition: 0.5s;
            filter: blur(15px);
            z-index: -1;
            opacity: 0;
        }

        .send li:hover::after {
            opacity: 0.5;
        }

        .send li .icon {
            font-size: 12px;
            transition: 0.5s;
            transition-delay: 0.25s;
        }

        .send li:hover .icon {
            transform: scale(0);
            color: #fff;
            transition-delay: 0s;
        }

        .send li span {
            position: absolute;
        }

        .send li .title {
            color: #fff;
            font-size: 1.1em;
            text-transform: uppercase;
            letter-spacing: 0.1em;
            transform: scale(0);
            transition: 0.5s;
            transition-delay: 0s;
        }

        .send li:hover .title {
            transform: scale(1);
            transition-delay: 0.25s;
        }

    }
}
</style>